'use strict';

const BaseService = require('./base');

class StudentService extends BaseService {
  constructor(ctx) {
    super(ctx, 'Student');
  }

  // 自定义排序规则
  pageOrder() {
    return [['grade', 'DESC'], ['class_name', 'ASC'], ['student_no', 'ASC']];
  }

  listOrder() {
    return this.pageOrder();
  }

  // 获取学生信息（包含家长信息）
  async findOne(id, withParent = true) {
    const include = withParent ? [{
      model: this.ctx.model.Parent,
      as: 'parent',
      attributes: ['id', 'name', 'phone', 'email']
    }] : [];

    return await this.ctx.model.Student.findOne({
      where: { id },
      include
    });
  }

  async findOneWithWhere(where) {
    return await this.ctx.model.Student.findOne({
      where,
    });
  }

  // 获取学生列表（分页，支持多条件筛选）
  async getPage(where, page, pageSize) {
    return await this.ctx.model.Student.findAndCountAll({
      where,
      offset: pageSize * (page - 1),
      limit: pageSize,
      order: this.pageOrder(),
      include: [{
        model: this.ctx.model.Parent,
        as: 'parent',
        attributes: ['id', 'name', 'phone']
      }]
    });
  }

  // 根据学号查询学生
  async findByStudentNo(student_no) {
    return await this.ctx.model.Student.findOne({
      where: { student_no }
    });
  }

  // 批量创建或更新学生
  async bulkCreateOrUpdate(students) {
    for (const student of students) {
      const { student_no } = student;
      const existingStudent = await await this.ctx.model.Student.findOne({
        where: {
          student_no,
          grade: student.grade,
          class_name: student.class_name
        }
      });
      if (existingStudent) {
        // 更新已存在的学生
        await this.update(existingStudent.id, student);
      } else {
        // 创建新学生
       await this.create(student);
      }
    }
  }

  // 获取班级列表
  async getClassList(where = {}) {
    return await this.ctx.model.Student.findAll({
      where,
      attributes: [
        'grade',
        'class_name',
      ],
      group: ['grade', 'class_name'],
      order: [['grade', 'DESC'], ['class_name', 'ASC']]
    });
  }
  async deleteAll() {
    // 删除选课
    await this.ctx.model.CourseRecord.destroy({ where: { } });
    // 删除家长绑定的学生
    await this.ctx.model.Parent.update({ student_id: 0 }, { where: { } });
    return await this.ctx.model.Student.destroy({ where: { } });
  }

  async deleteById(id) {
    // 删除选课
    await this.ctx.model.CourseRecord.destroy({ where: { student_id: id } });
    // 更新学生家长的学生id为空
    await this.ctx.model.Parent.update({ student_id: 0 }, { where: { student_id: id } });
    return await this.ctx.model[this.modelName].destroy({ where: { id } });
  }
}

module.exports = StudentService;
